package com.hundsun.s3.mrs.core.endpoint;


import java.net.BindException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class CoreEndPoint {
	
	public static final Logger LOG = LoggerFactory.getLogger(CoreEndPoint.class);
	
	public static final String ENDPOINT_NAME = "EndPoint";
	
	public boolean start(int port) {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workGroup = new NioEventLoopGroup();
		try {
			// ServerBootstrap 启动NIO服务的辅助启动类,负责初始话netty服务器，并且开始监听端口的socket请求
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workGroup);
			// 设置非阻塞,用它来建立新accept的连接,用于构造serversocketchannel的工厂类
			b.channel(NioServerSocketChannel.class);
			// ChildChannelHandler 对出入的数据进行的业务操作,其继承ChannelInitializer
			b.childHandler(new ChildChannelHandler());
			Channel ch = b.bind(port).sync().channel();
			ChannelManager.setPort(port);
			LOG.info("websocket服务启动成功，端口号为"+port);
			ch.closeFuture().sync();
			return true;
		} catch (Exception e) {
			if(e instanceof BindException) {
				LOG.error("端口：" + port +"已经被占用，准备以新的端口启动");
			} else {
				e.printStackTrace();
			}
			return false;
		}finally{
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
	}
	
}
